package com.banshuibao.bsb_android.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.MediaGrideListAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.ExpertTreeModel;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshGridView;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.PopuWindowsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by zyh on 2017/12/21.
 */

public class MediaListFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<GridView> {

    private PullToRefreshGridView pullToRefreshGridView;

    private GridView grideView;

    private MediaGrideListAdapter adapter;

    private LinearLayout indeustry, category, special;

    private TextView indeustry_tv, category_tv, special_tv;

    private ExpertTreeModel expertTreeModel;

    private PopupWindow popupWindow;

    private int sinceId = 1;

    private String uuid = "";

    private String type = "all";

    private MediaModel.Data data;

    private LinearLayout.LayoutParams params;

    private Dialog buyDialog;

    public MediaListFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_media_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pullToRefreshGridView = view.findViewById(R.id.pull);
        pullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshGridView.setOnRefreshListener(this);
        grideView = pullToRefreshGridView.getRefreshableView();
        grideView.setHorizontalSpacing(0);
        grideView.setNumColumns(2);//展示列数
        grideView.setVerticalScrollBarEnabled(false);
        //grideView.setDivider(null);
        Drawable drawable = getResources().getDrawable(R.drawable.noloading);
        ImageView imageView = new ImageView(getActivity());
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        imageView.setLayoutParams(params);
        imageView.setImageDrawable(drawable);
        grideView.setEmptyView(imageView);
        adapter = new MediaGrideListAdapter(getActivity());
        grideView.setAdapter(adapter);
        grideView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (adapter != null) {
                    MediaModel.Data data = adapter.getItem(i);
                    MediaListFragment.this.data = data;
                    buyMedia(data);
                }
            }
        });

        indeustry = view.findViewById(R.id.industry);
        indeustry_tv = view.findViewById(R.id.industry_tv);
        category = view.findViewById(R.id.category);
        category_tv = view.findViewById(R.id.category_tv);
        special = view.findViewById(R.id.special);
        special_tv = view.findViewById(R.id.special_tv);
        indeustry.setOnClickListener(l);
        category.setOnClickListener(l);
        special.setOnClickListener(l);
        getTreeData();
        loadNewData();
    }

    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            if (expertTreeModel == null) {
                getTreeData();
                return;
            }
            switch (view.getId()) {
                case R.id.industry:
                    indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                    showDialog(view, expertTreeModel.getData().get(0).getChildren(), indeustry_tv, "trade");
                    break;
                case R.id.category:
                    category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                    showDialog(view, expertTreeModel.getData().get(1).getChildren(), category_tv, "tax");
                    break;
                case R.id.special:
                    special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                    showDialog(view, expertTreeModel.getData().get(2).getChildren(), special_tv, "topic");
                    break;
            }
        }
    };

    /**
     * 行业税种专题数据
     */
    public void getTreeData() {
        HttpUtil.doPost(Constants.Url.EXPERT_TREE, null, new HttpResponse(getActivity(), ExpertTreeModel.class) {
            @Override
            public void onResult(Object obj) {
                expertTreeModel = (ExpertTreeModel) obj;
            }
        });
    }

    /**
     * 展示弹窗
     */
    public void showDialog(View view, List<ExpertTreeModel.DataBean.ChildrenBean> list, final TextView tv, final String type1) {
        PopuWindowsUtil popuWindowsUtil = new PopuWindowsUtil(getActivity());
        if (expertTreeModel == null) return;
        popupWindow = popuWindowsUtil.getP(list, null, "tree");
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
            }
        });
        PopuWindowsUtil.showAsDropDown(popupWindow, view, 0, 0);
        popuWindowsUtil.setContent(new PopuWindowsUtil.ItemOnClickListener() {
            @Override
            public void getContent(String name, String uuid) {
                if (!TextUtils.isEmpty(name)) {
                    defaultData();
                    MediaListFragment.this.uuid = uuid;
                    type = type1;
                    if (!TextUtils.equals("全部", name)) {
                        tv.setText(name);
                    } else {
                        setAll();
                    }
                    loadNewData();
                }
                if (popupWindow != null) popupWindow.dismiss();
            }
        });
    }

    private void setAll() {
        type = "all";
        this.uuid = "";
    }

    /**
     * 默认值
     */
    public void defaultData() {
        indeustry_tv.setText("行业");
        indeustry_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        category_tv.setText("税种");
        category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        special_tv.setText("专题");
        special_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        loadNewData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        loadMedia(uuid, type, sinceId, sinceId + 10);
    }

    private void loadNewData() {
        if (adapter != null) {
            int end = adapter.getCount() > 10 ? adapter.getCount() : 10;
            sinceId = 1;
            loadMedia(uuid, type, sinceId, end);
        }
    }

    private void loadMedia(String uuid, String type, final int s, final int e) {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(s);
        body.setMaxId(e);
        body.setType(type);
        body.setVideoType("1");
        body.setUuid(uuid);
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(getActivity(), MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                sinceId += mediaModel.getRows();
                if (adapter != null) {
                    if (s == 1) {
                        adapter.setData(mediaModel.getData());
                    } else
                        adapter.addData(mediaModel.getData());
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void buyMedia(final MediaModel.Data data) {
        if (QuickDoubleClickable.isDoubleClick())
            return;
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(data.getId());
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(getActivity()) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                    if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        IntentManager.goMediaPlayActivity(getActivity(), vid, Constants.Url.VIDEO, data.getId(), data.getImage());
                    } else {
                        buyDialog = DialogUtils.payDialog(getActivity(), "您可以支付" + String.valueOf(data.getPrice()) + "元购买单集或支付365元购买会员卡观看所有视频!",
                                data.getId(), String.valueOf(data.getPrice()), data.getTitle(), 4);
                        if (!buyDialog.isShowing())
                            buyDialog.show();
                        /*new AlertDialog.Builder(getActivity()).
                                setMessage("购买365会员可以免费观看所有视频,或者支付" + data.getPrice() + "元购买本集").
                                setPositiveButton("购买", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //IntentManager.goPayResultActivity(getActivity(), data.getTitle(), String.valueOf(data.getPrice()), data.getId(), 4);
                                        Intent intent = new Intent(getActivity(), PayActivity.class);
                                        intent.putExtra("flag", 4);
                                        intent.putExtra("content", data.getTitle());
                                        intent.putExtra("price", String.valueOf(data.getPrice()));
                                        intent.putExtra("uuid", data.getId());
                                        startActivityForResult(intent, 200);
                                    }
                                }).setNegativeButton("取消", null).create().show();*/
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200)
                buyMedia(MediaListFragment.this.data);
        }
    }

    private void pullComplete() {
        pullToRefreshGridView.onRefreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.clear();
            adapter = null;
        }
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
}
